package cn.tedu.service;

import cn.tedu.entity.AccountMessage;
import cn.tedu.entity.Order;
import cn.tedu.entity.TxInfo;
import cn.tedu.feign.AccountClient;
import cn.tedu.feign.EasyIdClient;
import cn.tedu.feign.StorageClient;
import cn.tedu.mapper.OrderMapper;
import cn.tedu.mapper.TxMapper;
import cn.tedu.service.OrderService;
import cn.tedu.util.JsonUtil;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;
import java.util.UUID;

/**
 * @author Administrator
 */
@Service
@RocketMQTransactionListener
public class OrderServiceImpl implements OrderService, RocketMQLocalTransactionListener {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private EasyIdClient easyIdClient;
    @Autowired
    private RocketMQTemplate t;
    @Autowired
    private TxMapper txMapper;

    //在监听器中,会调用这个方法
    public void doCreate(Order order) {
        // 远程调用ID发号器,获取订单ID
        Long id = Long.valueOf(easyIdClient.nextId("order_business"));
        order.setId(id);
        orderMapper.create(order);

    }

    @Override
    public void create(Order order) {
        String xid = UUID.randomUUID().toString().replace("-", "");
        AccountMessage am = new AccountMessage(order.getUserId(),order.getMoney(),xid);
        // am ---> json
        String json = JsonUtil.to(am);
        //spring封装的通用message对象
        //payLoad会自动被转成byte[]
        Message<String> message = MessageBuilder.withPayload(json).build();
        //发送事务消息
        //如果添加Tag,格式: "orderTopic:TagA"
        t.sendMessageInTransaction("orderTopic", message, order);
    }

    @Override
    @Transactional
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        RocketMQLocalTransactionState state; //用来返回数据
        int status;  //用来存储到数据库
        try {
            Order order = (Order) o;
            doCreate(order);  //保存订单
            state = RocketMQLocalTransactionState.COMMIT;
            status=0;
        } catch (Exception e) {
            e.printStackTrace();
            state=RocketMQLocalTransactionState.ROLLBACK;
            status=1;
        }
        //  TxInfo事务状态
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = new TxInfo(xid, status, System.currentTimeMillis());
        txMapper.insert(txInfo);
        return state;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String json = new String((byte[]) message.getPayload());
        String xid = JsonUtil.getString(json, "xid");
        TxInfo txInfo = txMapper.selectById(xid);
        if (txInfo == null){//查询事务状态
            return RocketMQLocalTransactionState.UNKNOWN;
        }
        switch (txInfo.getStatus()){
            case 0: return RocketMQLocalTransactionState.COMMIT;
            case 1: return RocketMQLocalTransactionState.ROLLBACK;
            default: return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
